<?php
/**
 * 控制器基类
 * 
 * @author Yucy<yucy1985@gmail.com>
 *
 */
class YucyController
{
	/**
	 * 
	 * 视图对象
	 * @var object
	 */
	private $_view;
	
	
	/**
	 * 
	 * 实例化类
	 */
	public function __construct()
	{
		// 控制器初始化
		$this->init();
	}
	
	
	/**
	 * 
	 * 初始化
	 */
	protected function init() {}
	
	
	/**
     * 
     * 获取视图对象
     * @param string $engine
     * @return View
     */
    protected function getView($engine = '')
    {
    	if ($this->_view) return $this->_view;
    	
    	if ($engine == '' && $engine !== NULL) $engine = YucyConfig::get('view_engine');
    	
		$this->_view = Yucy::getApp()->getHelper()->getView($engine);
		
		return $this->_view;
    }
    
    
    /**
     * 
     * 返回请求对象
     * @return Request
     */
    protected function getRequest()
    {
    	return Yucy::getApp()->getRequest();
    }
    
    
    /**
     * 
     * 返回响应对象
     * @return Response
     */
    protected function getResponse()
    {
    	return Yucy::getApp()->getResponse();
    }
    
    
    /**
     * 
     * 返回助手对象
     */
    protected function getHelper()
    {
    	return Yucy::getApp()->getHelper();
    }
    
    
    /**
     * 
     * 返回访客对象
     */
    protected function getVisitor()
    {
    	return Yucy::getApp()->getVisitor();
    }
    
    
    /**
     * 
     * 直接渲染文本
     * @param string $text
     */
    protected function renderText($text)
    {
    	Yucy::getApp()->getResponse()->setContent($text)->send();
    	exit;
    }
	
	
	/**
	 * 
	 * url跳转
	 * @param string $url
	 * @param int $code
	 */
	protected function redirect($url, $code = 302)
	{
		Yucy::getApp()->getResponse()->canSendHeaders(true);
		
       	Yucy::getApp()->getResponse()->setHeader('Location', $url, true)->setHttpCode($code)->sendHeaders();
        
        exit;
	}
	
	
	/**
	 * 
	 * 内部重定向
	 * @param string $actionName
	 * @param string $controllerName
	 * @param string $moduleName
	 */
	protected function forward($actionName, $controllerName = null, $moduleName = null)
	{
		$obj_dispatcher = Yucy::getApp()->resetDispatcher();
		if ($moduleName != null) $obj_dispatcher->setModuleName($moduleName);
		if ($controllerName != null) $obj_dispatcher->setControllerName($controllerName);	
		if ($actionName != null) $obj_dispatcher->setActionName($actionName);
		$obj_dispatcher->getController()->run();
		exit;
	}
	
	
	/**
	 * 
	 * 执行操作
	 */
	public function run()
	{
		// 获得当前的操作名
		$action_name = Yucy::getApp()->getDispatcher()->getActionName();
		if (empty($action_name)) return ;
		
		$action = $action_name . YucyConfig::get('action_suffix');
		if (!method_exists($this, $action)) throw new YucyException("类[" . get_class($this) . "]中找不到当前操作[{$action}]", 41);
		
		// 执行前置操作
		method_exists($this, $action_name . 'Before') && $this->{$action_name . 'Before'}();
		
		// 执行当前操作
		$this->{$action}();

		// 执行后置操作
		method_exists($this, $action_name . 'After') && $this->{$action_name . 'After'}();
		
		return ;
	}
}
?>